<template>
  <n-drawer v-model:show="isDrawer" :width="width" :auto-focus="false" @after-leave="handleReset">
    <n-drawer-content :title="title" closable>
      <n-form
        :model="formParams"
        :rules="rules"
        ref="formRef"
        label-placement="left"
        :label-width="100"
      >
        <n-form-item label="优惠券名称" path="name">
          <n-input placeholder="请输入优惠券名称" v-model:value="formParams.name" />
        </n-form-item>

        <n-form-item label="优惠券类型" path="type">
          <n-radio-group v-model:value="formParams.type" name="type">
            <n-space>
              <!-- 1:普通宝 2:快充宝 -->
              <n-radio :key="1" :value="1">普通宝</n-radio>
              <n-radio :key="2" :value="2">快充宝</n-radio>
            </n-space>
          </n-radio-group>
        </n-form-item>

        <n-form-item label="减免类型" path="attr">
          <n-radio-group v-model:value="formParams.attr" name="attr">
            <n-space>
              <!-- 1:金额 2:时长 -->
              <n-radio :key="1" :value="1">金额</n-radio>
              <n-radio :key="2" :value="2">时长</n-radio>
            </n-space>
          </n-radio-group>
        </n-form-item>

        <n-form-item label="金额(元)或时长(小时)" path="minus">
          <n-input-number placeholder="请输入减免金额(元)或时长(小时)" clearable v-model:value="formParams.minus" />
        </n-form-item>

        <n-form-item label="数量" path="num">
          <n-input placeholder="请输入数量" :allow-input="onlyAllowNumber" clearable v-model:value="formParams.num" />
        </n-form-item>

        <n-form-item label="过期时间" path="expired_at">
          <n-date-picker
            v-model:value="timestamp"
            value-format="yyyy-MM-dd HH:mm:ss"
            type="datetime"
            clearable
            :format="format"
          />
        </n-form-item>
      </n-form>

      <template #footer>
        <n-space>
          <n-button @click="handleReset">重置</n-button>
          <n-button type="primary" :loading="subLoading" @click="formSubmit">提交</n-button>
        </n-space>
      </template>

    </n-drawer-content>
  </n-drawer>
</template>

<script lang="ts" setup>
  import { ref } from 'vue';
  import { useMessage, FormRules } from 'naive-ui';
  // import type { formParamsType } from './types';
  // import { useDictionary } from '@/hooks/web/useDictionary';

  import { add, edit, info } from '@/api/coupons/coupons';

  const rules: FormRules = {
    name: {
      required: true,
      message: '名称不能为空',
      trigger: 'blur',
    }
  };

  const emit = defineEmits(['change']);
  // const { getDictTypeList } = useDictionary();

  const props = defineProps({
    title: {
      type: String,
      default: '添加优惠券',
    },
    width: {
      type: Number,
      default: 850,
    },
    roleList: {
      type: Array,
    },
  });

  const defaultValueRef = () => ({
    id: null,
    name: '',
    type: 1,
    attr: 1,
    minus: '',
    num: '',
    expired_at: '',
  });
  const onlyAllowNumber = (value: string) => !value || /^\d+$/.test(value);
  const timestamp = ref(null);
  const format = 'yyyy-MM-dd HH:mm:ss';
  const message = useMessage();
  const formRef: any = ref(null);
  const isDrawer = ref(false);
  const subLoading = ref(false);
  // const agentAll = ref([]);

  const formParams = ref(defaultValueRef());

  async function openDrawer(id?) {
    if (id) {
      formParams.value.id = id;
      getInfo();
      return;
    }
    isDrawer.value = true;
  }

  function closeDrawer() {
    isDrawer.value = false;
  }

  function formSubmit() {
    formRef.value.validate((errors) => {
      if (!errors) {
        formParams.value.expired_at = timestamp.value;

        const msg = formParams.value.id ? '编辑成功' : '添加成功';

        if (formParams.value.id) {
          edit(formParams.value).then((_) => {
            message.success(msg);
            emit('change');
            handleReset();
            closeDrawer();
          });
        } else {
          add(formParams.value).then((_) => {
            message.success(msg);
            emit('change');
            handleReset();
            closeDrawer();
          });
        }
      } else {
        message.error('请填写完整信息');
      }
    });
  }

  function handleReset() {
    formRef.value.restoreValidation();
    formParams.value = Object.assign(formParams.value, defaultValueRef());
  }

  function getInfo() {
    info({ id: formParams.value.id }).then((res) => {
      const params = {
        id: formParams.value.id,
        name: res.name,
        type: parseInt(res.type),
        discount: res.discount,
        full: res.full,
        minus: res.minus,
        num: res.num,
        expired_at: res.expired_at,
      };

      timestamp.value = convertToTimestamp(res.expired_at);

      formParams.value = Object.assign(formParams.value, params);
      isDrawer.value = true;
    });
  }

  function convertToTimestamp(dateString) {
    var date = new Date(dateString);
    return date.getTime();
}

  defineExpose({
    openDrawer,
    closeDrawer,
  });
</script>
